use std::env::args;
use std::fs::File;
use std::io::BufWriter;
use chksum_md5 as md5;
use chksum_md5::new;
use local_ip_address::local_ip;
use log::{error, info};
use pdf::build::{CatalogBuilder, Importer, PageBuilder, PdfBuilder};
use pdf::file::FileOptions;
use pdf::font;
use pdf::object::Updater;
use serde::{Deserialize, Serialize, Serializer};

pub fn md5(str: String) -> String {
    if let Ok(d) = md5::chksum(&str) {
        return d.to_string();
    };
    String::new()
}

pub fn to_json_string<T: ?Sized + Serialize>(v: &T) -> Option<String> {
    match serde_json::to_string(v) {
        Ok(s) => {
            // println!("ssss->>{}", s);
            // if s.contains("\\\"") && s.contains("{") {
            //     // let d = s.replace("\\\"", "\"");
            //     Some(s)
            // } else {
            Some(s)
            // }
        }
        Err(e) => {
            error!("序列化错误->{}",e);
            None
        }
    }
}

pub fn json_to_dto<'a, T: Deserialize<'a>>(str: &'a String) -> Option<T> {
    if str.is_empty() {
        return None;
    }
    match serde_json::from_slice(str.as_bytes()) {
        Ok(s) => Some(s),
        Err(e) => {
            error!("反序列化错误->{}-{}",e,str);
            None
        }
    }
}


#[cfg(test)]
#[test]
pub fn test_pdf() {
    use pdf::file::File as PFile;
    use std::fs::File;
    use std::io::BufWriter;
    let input_file_path = "D:\\tmp\\input.pdf";
    // let input_file = File::open(input_file_path).expect("Failed to open input file");
    let old_file = FileOptions::cached().open(input_file_path).unwrap();
    // let input_pdf = PFile::open(input_file).unwrap();
    for (page_num, page) in old_file.pages().enumerate() {
        let output_file_path = format!("D:\\tmp\\pdfsp-{}.pdf", page_num + 1);
        if let Ok(p) = page {
            let mut builder = PdfBuilder::new(FileOptions::cached());
            let mut importer = Importer::new(old_file.resolver(), &mut builder.storage);
            let mut pages = Vec::new();
            let mut new_page = PageBuilder::clone_page(&p, &mut importer).unwrap();
            pages.push(new_page);
            let catalog = CatalogBuilder::from_pages(pages);
            importer.finish().verify(&builder.storage.resolver()).unwrap();
            let data = builder.build(catalog).unwrap();
            std::fs::write(output_file_path, data).unwrap();
        }
    }
}